﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using X.PagedList;
using XbsWebAPI.Application.QueryModel;
using XbsWebAPI.Application.RoomStatus.Dtos;
using XbsWebAPI.Core.Repositories;
using XbsWebAPI.EntityFrameworkCore.Entities;
using XbsWebAPI.EntityFrameworkCore.Entities.Enums;
using XbsWebAPI.EntityFrameworkCore.Entities.RoomStatus;

namespace XbsWebAPI.Application
{
    public class RoomStatusAppService : IRoomStatusAppService
    {
        private readonly IMapper _mapper;
        private readonly IHouseTypeRepository _houseTypeRepository;
        private readonly IRoomStatusRepository _roomStatusRepository;
        private readonly IRoomRepository _roomRepository;
        private readonly ICheckInRepository _checkInRepository;
        private readonly IOrderRepository _orderRepository;

        public RoomStatusAppService(IMapper mapper, IHouseTypeRepository houseTypeRepository,IRoomStatusRepository roomStatusRepository,IRoomRepository roomRepository, ICheckInRepository checkInRepository,IOrderRepository orderRepository)
        {
            _mapper = mapper;
            _houseTypeRepository = houseTypeRepository;
            _roomStatusRepository = roomStatusRepository;
            _roomRepository = roomRepository;
            _checkInRepository = checkInRepository;
            _orderRepository = orderRepository;
        }


        public void InitRoomStatusSign()
        {
            //            public RoomUsingStatus RoomUsingStatus { get; set; }

            //public Guid? RoomId { get; set; }

            //public Guid? HouseTypeId { get; set; }

            //public Guid? CampId { get; set; }

            //public DateTime UseDate { get; set; }

            //public Guid? OrderId { get; set; }

            //public Guid? CheckInId { get; set; }
            var signs = new List<RoomStatusSign>();

            for (int i = 2; i <= 10; i++)
            {
                if(i == 5 || i == 6)
                {
                    continue;
                }

                var sign = new RoomStatusSign()
                {
                    RoomUsingStatus = RoomUsingStatus.Living,
                    RoomId = new Guid("75aafe6d-03dc-4741-abdb-2896b206ffab"),
                    HouseTypeId = new Guid("1258d19b-6100-4db3-a087-3eec440f3fbf"),
                    CampId = null,
                    UseDate = new DateTime(2022, 3, i),
                    CheckInId = new Guid("9ce202bc-6fe3-4a90-9c5f-4346b7b51d6a")
                };
            }

            
        }



        public ResultDto<List<RoomStatusFilterDto>> GetSelectRoomStatusFilters(DateTime? useDate,Guid? campId,Guid? houseTypeId)
        {
            var result = new ResultDto<List<RoomStatusFilterDto>>();

            try
            {
                useDate = useDate == null ? new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day) : useDate.Value;

                var roomStatusSigns = _roomStatusRepository.AsQueryable().Where(a => a.UseDate == useDate);

                if (houseTypeId.HasValue)
                {
                    roomStatusSigns = roomStatusSigns.Where(a => a.HouseTypeId == houseTypeId);
                }
                if (campId.HasValue)
                {
                    roomStatusSigns = roomStatusSigns.Where(a => a.CampId == campId);
                }
                //if (query.UseDate.HasValue)
                //{
                //    roomStatusSigns.Where(a => a.UseDate.Year == query.UseDate.Value.Year && a.UseDate.Month == query.UseDate.Value.Month && a.UseDate.Day == query.UseDate.Value.Day);
                //}

                var resultList = roomStatusSigns.ToList();
                //总房间个数
                var roomsCount = _roomRepository.AsQueryable().Count();

                //当天房间在使用的个数
                var statusRoomsCount = resultList.Select(a => a.RoomId).Distinct().Count();

                var list = new List<RoomStatusFilterDto>()
            {
                new RoomStatusFilterDto
                {
                    RoomUsingStatus = RoomUsingStatus.Free,
                    Count = roomsCount - statusRoomsCount,
                },
                new RoomStatusFilterDto
                {
                    RoomUsingStatus = RoomUsingStatus.Living,
                    Count = roomStatusSigns.Where(a => a.RoomUsingStatus == RoomUsingStatus.Living).Count(),
                },
                new RoomStatusFilterDto
                {
                    RoomUsingStatus = RoomUsingStatus.Booking,
                    Count = roomStatusSigns.Where(a => a.RoomUsingStatus == RoomUsingStatus.Booking).Count(),
                },
                new RoomStatusFilterDto
                {
                    RoomUsingStatus = RoomUsingStatus.ToBeContinueToLive,
                    Count = roomStatusSigns.Where(a => a.RoomUsingStatus == RoomUsingStatus.ToBeContinueToLive).Count(),
                },
                new RoomStatusFilterDto
                {
                    RoomUsingStatus = RoomUsingStatus.ToCheckOut,
                    Count = roomStatusSigns.Where(a => a.RoomUsingStatus == RoomUsingStatus.ToCheckOut).Count(),
                },
            };

                result.Result = list;
                result.Message = "操作成功";
            }
            catch (Exception e)
            {
                result.Message = e.Message;
                result.Code = -1;
                return result;
            }

            return result;
        }

        public ResultDto<List<SelectHouseTypeDto>> GetSelectHouseTypes()
        {
            var result = new ResultDto<List<SelectHouseTypeDto>>();

            try
            {
                var houseTypes = _houseTypeRepository.AsQueryable().ToList();
                var houseTypeDtos = houseTypes.Select(e => _mapper.Map<SelectHouseTypeDto>(e)).ToList();

                result.Code = 0;
                result.Message = "操作成功";
                result.Result = houseTypeDtos;
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                result.Result = null;
                return result;
            }


            return result;
        }

        public ResultDto<List<RoomStatusSignDto>> GetRoomStatusSigns(QueryRoomStatus query)
        {
            var result = new ResultDto<List<RoomStatusSignDto>>();
            var roomStatusSigns = new List<RoomStatusSignDto>();
            var rooms = _roomRepository.AsQueryable().Include(a => a.HouseType).ToList();

            try
            {
                query.UseDate = query.UseDate == null ? new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day) : query.UseDate.Value;

                var queryList = _roomStatusRepository.AsQueryable().Where(a => a.UseDate == query.UseDate);

                if (query.HouseTypeId.HasValue)
                {
                    queryList = queryList.Where(a => a.HouseTypeId == query.HouseTypeId.Value);
                    rooms = rooms.Where(a => a.HouseTypeId.Value == query.HouseTypeId.Value).ToList();
                }
                if (query.CampId.HasValue)
                {
                    queryList = queryList.Where(a => a.CampId == query.CampId.Value);
                    rooms = rooms.Where(a => a.HouseType.CampId == query.CampId.Value).ToList();
                }
                if (query.RoomUsingStatus.HasValue)
                {
                    queryList = queryList.Where(a => a.RoomUsingStatus == query.RoomUsingStatus);
                }

                //筛选出来有状态的房间
                var resultList = queryList.ToList();
                


                if (query.RoomUsingStatus.HasValue)
                {
                    //rooms = new List<Room>();
                    if (query.RoomUsingStatus == RoomUsingStatus.Free)
                    {
                        //rooms = _roomRepository.AsQueryable().ToList();
                        foreach (var roomSign in resultList)
                        {
                            var room = rooms.Find(a => a.Id == roomSign.RoomId);
                            if (room != null)
                            {
                                rooms.Remove(room);
                            }
                        }
                    }
                    else
                    {
                        rooms = new List<Room>();
                        foreach (var roomSign in resultList)
                        {
                            var room = _roomRepository.QueryById(roomSign.RoomId.Value);
                            if (roomSign.RoomUsingStatus == query.RoomUsingStatus)
                            {
                                rooms.Add(room);
                            }
                        }
                    }

                }
                //else
                //{
                //    rooms = _roomRepository.AsQueryable().ToList();
                //}

                foreach (var room in rooms)
                {
                    var sign = resultList.AsQueryable().FirstOrDefault(a => a.RoomId == room.Id);
                    var roomStatusSign = new RoomStatusSignDto();

                    //默认设置空闲房间
                    roomStatusSign.RoomId = room.Id;
                    roomStatusSign.RoomName = room.Name;
                    roomStatusSign.RoomUsingStatus = RoomUsingStatus.Free;

                    if (sign != null)
                    {
                        var order = _orderRepository.AsQueryable().FirstOrDefault(a => a.OrderNumber == sign.OrderNumber);
                        roomStatusSign.RoomUsingStatus = sign.RoomUsingStatus;
                        if (order == null)
                        {
                            throw new Exception($"当前订单{sign.OrderNumber}不存在");
                        }

                        roomStatusSign.RoomUsingStatus = sign.RoomUsingStatus;
                        if (sign.RoomUsingStatus != RoomUsingStatus.Free && sign.RoomUsingStatus != RoomUsingStatus.CheckedOut)
                        {
                            roomStatusSign.OrderId = order.Id;
                            roomStatusSign.BookingPerson = order.Guests;
                            roomStatusSign.BookingPhoneNumber = order.PhoneNumber;
                            
                        }

                    }
                    roomStatusSigns.Add(roomStatusSign);
                }

                result.Result = roomStatusSigns;
                result.Message = "操作成功";
            }
            catch (Exception e)
            {
                result.Message = e.Message;
                result.Code = -1;
                return result;
            }
            

            return result;
        }

        public Task<ResultDto<string>> CancelBookingOrder(Guid orderId)
        {
            var result = new ResultDto<string>();
            using(var ts = new TransactionScope())
            {
                try
                {
                    //查询订单详情
                    var order = _orderRepository.QueryById(orderId);

                    //将订单OrderStatus=cancel更新
                    order.OrderStatus = OrderStatus.Cancel;
                    _orderRepository.UpdateAsync(order);

                    //查询占坑的RoomStatusSign集合，改为空闲
                    var roomSigns = _roomStatusRepository.AsQueryable().Where(a => a.OrderNumber == order.OrderNumber).ToList();
                    if (roomSigns != null && roomSigns.Count > 0)
                    {
                        foreach (var roomStatusSign in roomSigns)
                        {
                            roomStatusSign.RoomUsingStatus = RoomUsingStatus.Free;
                            _roomStatusRepository.UpdateAsync(roomStatusSign);
                        }
                    }

                    //查询房间，将房间RoomUsingStatus=Free
                    var room = _roomRepository.QueryById(order.RoomId.Value);
                    room.RoomUsingStatus = RoomUsingStatus.Free;
                    _roomRepository.UpdateAsync(room);
                    result.Message = "操作成功";
                    ts.Complete();
                }
                catch (Exception e)
                {
                    result.Message = e.Message;
                    result.Code = -1;
                    return Task.FromResult(result);
                }
            }

            return Task.FromResult(result);
        }

        public ResultDto<RoomStatusCheckOutDetaiDto> GetCheckOutRoomDetail(Guid orderId)
        {
            var result = new ResultDto<RoomStatusCheckOutDetaiDto>();
            var dto = new RoomStatusCheckOutDetaiDto();
            var order = _orderRepository.QueryById(orderId);
            if (order == null)
            {
                throw new Exception($"订单ID={orderId}不存在");
            }

            if (order.RoomId == null)
            {
                throw new Exception($"订单的roomId为空");
            }

            var room = _roomRepository.QueryById(order.RoomId.Value);

            if(room == null)
            {
                throw new Exception($"订单的房间不存在");
            }

            dto.CheckInDate = order.CheckInDate.ToString("yyyy-MM-dd");
            dto.CheckOutDate = order.CheckOutDate.ToString("yyyy-MM-dd");
            dto.HouseTypeName = order.HouseTypeName;
            dto.OrderId = order.Id;
            dto.RoomName = room.Name;

            var totalDays = (order.CheckOutDate - order.CheckInDate).Days;
            var useDays = (Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")) - order.CheckInDate).Days;
            dto.TotalDays = totalDays;
            dto.UseDays = useDays <= 0 ? 0 : useDays;

            result.Result = dto;
            result.Message = "操作成功";

            return result;
        }
    }


}
